// pages/player/index.js
//因为这个数据不需要在界面上显示，所以定义在这里
let musiclist=[];
//正在播放歌曲的index
let nowPlayingIndex=-1;
// 获取全局唯一的背景音频管理器
const backgroundAudioManager = wx.getBackgroundAudioManager()
Page({

  /**
   * 页面的初始数据
   */
  data: {
      picUrl:'',
      isPlaying: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    musiclist=wx.getStorageSync("musiclist");
    nowPlayingIndex=options.index;
    this._loadMusicDetail(options.musicId);
  },
  _loadMusicDetail(musicId){
    backgroundAudioManager.stop();
    let music=musiclist[nowPlayingIndex];
    wx.setNavigationBarTitle({
      title: music.name,
    })
    this.setData({
      picUrl:music.al.picUrl,
      isPlaying : false
    })
    console.log('getApp().globalData.baseUrl+`/song/url?id=${musicId}`',getApp().globalData.baseUrl+`/song/url?id=${musicId}`);
    console.log('music',music);
    wx.showLoading({
      title: '歌曲加载中',
    })
    wx.request({
      method:'POST',
      dataType:'json',
      enableHttp2:true,
      url: getApp().globalData.baseUrl+`/song/url?id=${musicId}`,
      success: (res)=>{
        console.log('res.data.data',res.data.data);
        backgroundAudioManager.title =music.name;
        backgroundAudioManager.epname = music.al.name;
        backgroundAudioManager.singer = music.ar.name;
        backgroundAudioManager.coverImgUrl =music.al.picUrl;
        // 设置了 src 之后会自动播放
        backgroundAudioManager.src = res.data.data[0].url.replace("http","https")
        this.setData({
          isPlaying:true
        })
        wx.hideLoading();
      }
    })
 
  },
  togglePlaying(){
    if(this.data.isPlaying){
      backgroundAudioManager.pause();
    }else{
      backgroundAudioManager.play();
    }
    this.setData({
      isPlaying:!this.data.isPlaying
    })
  },
  onPrev(){
    nowPlayingIndex--
    if(nowPlayingIndex<0){
      nowPlayingIndex=musiclist.length-1
    }
    console.log('nowPlayingIndex',nowPlayingIndex);
    this._loadMusicDetail(musiclist[nowPlayingIndex].id);
  },
  onNext(){
    nowPlayingIndex++
    if(nowPlayingIndex>=musiclist.length){
      nowPlayingIndex=0
    }
    console.log('nowPlayingIndex',nowPlayingIndex);
    this._loadMusicDetail(musiclist[nowPlayingIndex].id);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})